package com.business.components.tree.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.common.URL;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.business.components.tree.po.TreeBean;
import com.business.components.tree.service.TreeService;
import com.common.ErrorLog;
import com.common.NumberProcess;
import com.common.RenderPage;
import com.common.StringProcess;

@Controller
@RequestMapping(value = "/components/tree")
public class TreeController {
	
	@Autowired
	private TreeService treeService;
	
	private static String temp = null;
	
	private boolean isLazy = false;
	private int selectType = 0;
	private int expandType = 3;
	private boolean onlyLeafSelect = false;
	private String topLevelValue = "";

	@RequestMapping({ "/treeDialog" })
	public String treeDialog(ModelMap model,HttpServletRequest request) {
		
		String dataMapper=StringProcess.getRequest(request.getParameter("dataMapper"), "");
		String searchMapper=StringProcess.getRequest(request.getParameter("searchMapper"), "");
		
		Map<String,Object> search=JSON.parseObject(searchMapper, new TypeReference<Map<String,Object>>(){});
		String multiValueKey=StringProcess.convertToString(search.get("multiValueKey"));
		if(multiValueKey.length()>0)
		{
			//单个multiValueKey
			String value=search.get(multiValueKey).toString();
			if(value.length()>0)
			{
				String[] valueArray=value.split(",");
				search.put(multiValueKey, valueArray);
			}
			
		}
				
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		String db="";
		String[] array=dataMapper.split("\\.");
		if(array.length>2)
		{
			db=array[0];
		}
		if(db.equals("frame"))
		{
			list = treeService.SelectFrame(dataMapper,search);
		}
		else if(db.equals("form"))
		{
			list = treeService.SelectForm(dataMapper,search);
		}
		else
		{
			list = treeService.SelectBusiness(dataMapper,search);
		}
		
		for(int i=0;i<list.size();i++)
		{
			Map<String, Object> item = list.get(i);
			item.put("ReturnValue", StringProcess.encode(JSON.toJSONString(item)));
		}
		
		/*
		List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> item;
		
		item = new HashMap<String, Object>();
		item.put("ParentNodeId", "0");
		item.put("NodeId", "37");
		item.put("NodeCode", "37");
		item.put("NodeText", "山东");
		list.add(item);
		
		item = new HashMap<String, Object>();
		item.put("ParentNodeId", "37");
		item.put("NodeId", "3701");
		item.put("NodeCode", "3701");
		item.put("NodeText", "济南市");
		item.put("ReturnValue", StringProcess.encode(JSON.toJSONString(item)));
		list.add(item);
		
		item = new HashMap<String, Object>();
		item.put("ParentNodeId", "37");
		item.put("NodeId", "3702");
		item.put("NodeCode", "3702");
		item.put("NodeText", "青岛市");
		item.put("ReturnValue", StringProcess.encode(JSON.toJSONString(item)));
		list.add(item);
		
		item = new HashMap<String, Object>();
		item.put("ParentNodeId", "37");
		item.put("NodeId", "3703");
		item.put("NodeCode", "3703");
		item.put("NodeText", "淄博市");
		item.put("ReturnValue", StringProcess.encode(JSON.toJSONString(item)));
		list.add(item);
		*/
		
		String treeData=JSON.toJSONString(list);
		treeData = StringProcess.encode(treeData);
		model.put("treeData", treeData);
		
		List<Map<String,Object>> initList = new ArrayList<Map<String, Object>>();
		String initData="";
		String currentId=StringProcess.getRequest(request.getParameter("currentId"), "");
		if(currentId.length()>0)
		{
			String[] currentArray = currentId.split(",");
			for(String currentItem:currentArray)
			{
				for(int i=0;i<list.size();i++)
				{
					if(currentItem.equals(list.get(i).get("NodeId")))
					{
						String returnValue = list.get(i).get("ReturnValue").toString();
						returnValue = StringProcess.decode(returnValue);
						Map<String,Object> aaa =JSON.parseObject(returnValue, new TypeReference<Map<String,Object>>(){});
						initList.add(aaa);
					}
				}
			}
		}
		initData=JSON.toJSONString(initList);
		initData = StringProcess.encode(initData);
		model.put("initData", initData);
		
		String selectType = StringProcess.getRequest(request.getParameter("selectType"), "0");
		model.put("selectType", selectType);
		
		String expandType = StringProcess.getRequest(request.getParameter("expandType"), "3");
		model.put("expandType", expandType);
		
		String onlyLeafSelect = StringProcess.getRequest(request.getParameter("onlyLeafSelect"), "false");
		model.put("onlyLeafSelect", onlyLeafSelect);
		 
		return "components/tree/treedialog";
	}
	
	@RequestMapping({ "/show" })
	public String show(ModelMap model,HttpServletRequest request) {
		
		String dataMapper=StringProcess.getRequest(request.getParameter("dataMapper"), "");
		
		Map<String,Object> search;
		String searchMapper=StringProcess.getRequest(request.getParameter("searchMapper"), "");
		if(searchMapper.length()==0)
		{
			search=new HashMap<String, Object>();
		}
		else
		{
			search = JSON.parseObject(searchMapper, new TypeReference<Map<String,Object>>(){});
		}
		
		List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
		String db="";
		String[] array=dataMapper.split("\\.");
		if(array.length>2)
		{
			db=array[0];
		}
		if(db.length()>0)
		{
			if(db.equals("frame"))
			{
				list = treeService.SelectFrame(dataMapper,search);
			}
			else if(db.equals("form"))
			{
				list = treeService.SelectForm(dataMapper,search);
			}
			else 
			{
				list = treeService.SelectBusiness(dataMapper,search);
			}	
		}
		
		String clickScript=StringProcess.getRequest(request.getParameter("clickScript"), "");
		if(clickScript.length()>0)
		{
			for(int i=0;i<list.size();i++)
			{
				Map<String,Object> item=list.get(i);
				
				String currentScript=clickScript;
				currentScript=currentScript.replace("url.NodeId", item.get("NodeId").toString());
				currentScript=currentScript.replace("url.ParentNodeId", item.get("ParentNodeId").toString());
				item.put("ClickScript", currentScript);
			}
		}

		
		
		String treeData=JSON.toJSONString(list);
		treeData = StringProcess.encode(treeData);
		model.put("treeData", treeData);
		
		List<Map<String,Object>> initList = new ArrayList<Map<String, Object>>();
		String initData=JSON.toJSONString(initList);
		initData = StringProcess.encode(initData);
		model.put("initData", initData);
		
		String expandType = StringProcess.getRequest(request.getParameter("expandType"), "3");
		model.put("expandType", expandType);

		return "components/tree/show";
	}
	
	@RequestMapping({ "/demo" })
	public String demo(ModelMap model) {
		
		List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> item;
		
		item = new HashMap<String, Object>();
		item.put("ParentNodeId", "0");
		item.put("NodeId", "37");
		item.put("NodeText", "山东");
		item.put("ReturnValue", "");
		list.add(item);
		
		item = new HashMap<String, Object>();
		item.put("ParentNodeId", "37");
		item.put("NodeId", "3701");
		item.put("NodeText", "济南市");
		list.add(item);
		
		item = new HashMap<String, Object>();
		item.put("ParentNodeId", "37");
		item.put("NodeId", "3702");
		item.put("NodeText", "青岛市");
		list.add(item);
		
		item = new HashMap<String, Object>();
		item.put("ParentNodeId", "3702");
		item.put("NodeId", "370202");
		item.put("NodeText", "市南区");
		list.add(item);
		
		item = new HashMap<String, Object>();
		item.put("ParentNodeId", "37");
		item.put("NodeId", "3703");
		item.put("NodeText", "淄博市");
		list.add(item);
		
		String treeData=JSON.toJSONString(list);
		treeData = StringProcess.encode(treeData);
		model.put("treeData", treeData);
		
		List<Map<String,Object>> initList = new ArrayList<Map<String, Object>>();
		String initData=JSON.toJSONString(initList);
		initData = StringProcess.encode(initData);
		model.put("initData", initData);

		return "components/tree/show";
	}
	
	@RequestMapping({ "/tree" })
	public String tree(ModelMap model) {

		return "components/tree/tree";
	}
	
	@RequestMapping("/read")
	public void read(HttpServletRequest request, HttpServletResponse response, String tempHtml) {
			
		try
		{
			String result = "";
			
			if(temp==null)
			{
				temp = tempHtml;
			}
			
			String treeData = request.getParameter("treeData");
			String initData = request.getParameter("initData");
			
			topLevelValue = request.getParameter("topLevelValue");
			isLazy = request.getParameter("isLazy").equals("true")?true:false;
			selectType = NumberProcess.convertToNumber(request.getParameter("selectType"));
			expandType = NumberProcess.convertToNumber(request.getParameter("expandType"));
			onlyLeafSelect = request.getParameter("onlyLeafSelect").equals("true")?true:false;
			
			
			List<Map<String,Object>> list =JSON.parseObject(treeData, new TypeReference<List<Map<String,Object>>>(){});
			List<Map<String,Object>> initList=JSON.parseObject(initData, new TypeReference<List<Map<String,Object>>>(){});
			result = processData(list,initList,topLevelValue,"","");
			
			RenderPage.JsonByString(response, result);
			
		}
		catch(Exception e)
		{
			ErrorLog.OnWrite(e);
		}
		
	}
	
	private String processData(List<Map<String,Object>> dataMap, List<Map<String,Object>> initData,String parentId,String isLast,String preLine)
	{
		StringBuilder sb = new StringBuilder();
		
		TreeBean parentNode=null;
		if(parentId.equals(topLevelValue))
		{
			
		}
		else
		{
			parentNode = new TreeBean();
			parentNode.setLast(isLast.equals("1")?true:false);
			parentNode.setPreLine(preLine);
		}
		
		List<TreeBean> list = dataTableToNode(dataMap, initData, parentId);
		
		//List<TreeBean>转成HTML
		for(TreeBean item : list)
		{
			String currentTemp = temp;
			
			sb.append(nodeToHTML(currentTemp,parentNode,item,isLazy));
		}
		
		return sb.toString();
	}
	
	private String nodeToHTML(String currentTemp, TreeBean parentNode, TreeBean item, boolean isLazy)
	{
		String treeLine="";
		if(parentNode!=null)
		{
			treeLine += StringProcess.convertToString(parentNode.getPreLine());
			
			if(parentNode.isLast())
			{
				treeLine += "<div class=\"Line\"></div>";
			}
			else
			{
				treeLine += "<div class=\"Line Line2\"></div>";
			}
			
			if(parentNode.getSelectType().equals("radio") || parentNode.getSelectType().equals("checkbox"))
			{
				treeLine += "<div class=\"Control\"></div>";
			}
			item.setPreLine(treeLine);
		}
		
		String lineType = "";
		if(item.isLast())
		{
			 lineType = " Line3";
		}
		else
		{
			lineType = " Line1";
		}
		
		String hasChild = "";
		if (isLazy)
		{
			if (parentNode == null)
			{
				hasChild = String.format("<div class=\"Button Init\" id=\"expand_%s\" AjaxFileName=\"%s\"></div>", item.getNodeId(),item.getAjaxFileName());
			}
			else
			{
				hasChild = String.format("<div class=\"Button Init\" id=\"expand_%s\" AjaxFileName=\"%s\" IsLast=\"%s\" PreLine=\"%s\"></div>", item.getNodeId(),item.getAjaxFileName(),item.isLast()?"1":"0",item.getPreLine());
			}
		}
		else
		{
			if(item.getChildNodes().size()>0)
			{
				if(expandType==0)
				{
					if (parentNode == null)
					{
						hasChild = String.format("<div class=\"Button Close\" id=\"expand_%s\"></div>", item.getNodeId());
					}
					else
					{
						hasChild = String.format("<div class=\"Button Open\" id=\"expand_%s\"></div>", item.getNodeId());
					}
				}
				else if(expandType==1)
				{
					hasChild = String.format("<div class=\"Button Close\" id=\"expand_%s\"></div>", item.getNodeId());
				}
				else if(expandType==3)
				{
					hasChild = String.format("<div class=\"Button Open\" id=\"expand_%s\"></div>", item.getNodeId());
				}
			}
			else
			{
				hasChild = "";
			}
		}
		
		String showHide = "";
		if(item.getSelectType().length()==0)
		{
			showHide = " style=\"display:none;\"";
		}
		
		String clickEvent = "";
		String clickScript = item.getClickScript();
		if (clickScript != null && clickScript.length() > 0)
		{
			clickEvent = String.format(" onclick=\"%s\"", clickScript);
		}
		
		String expanyTypeHtml = "";
        if (expandType == 0)
        {
            if (parentNode == null)
            {
                expanyTypeHtml = "";
            }
            else
            {
                expanyTypeHtml = " style=\"display:none;\"";
            }
        }
        else if (expandType == 1)
        {
            expanyTypeHtml = "";
        }
        else if (expandType == 3)
        {
            expanyTypeHtml = " style=\"display:none;\"";
        }
        
        String childNode = "";
        if(!isLazy)
        {
        	List<TreeBean> list = item.getChildNodes();
        	if(list.size()>0)
        	{
        		for(TreeBean node : list)
        		{
        			childNode += nodeToHTML(temp, item, node, isLazy);
        		}
        	}
        }
        
        String message = "";
        if(item.isSelect())
        {
        	//message = "初始化";
        }
        
        currentTemp = currentTemp.replace("{NodeId}", item.getNodeId());
        currentTemp = currentTemp.replace("{TreeLine}", treeLine);
        currentTemp = currentTemp.replace("{LineType}", lineType);
        currentTemp = currentTemp.replace("{HasChild}", hasChild);
        currentTemp = currentTemp.replace("{SelectType}", item.getSelectType());
        currentTemp = currentTemp.replace("{ShowHide}", showHide);
        currentTemp = currentTemp.replace("{NodeText}", item.getNodeText());
        currentTemp = currentTemp.replace("{ClickEvent}", clickEvent);
        currentTemp = currentTemp.replace("{ExpanyType}", expanyTypeHtml);
        currentTemp = currentTemp.replace("{ChildNode}", childNode);
        currentTemp = currentTemp.replace("{ReturnValue}", item.getReturnValue());
        currentTemp = currentTemp.replace("{Message}", message);
		
		return currentTemp;
	}
	
	private List<TreeBean> dataTableToNode(List<Map<String,Object>> dataMap, List<Map<String,Object>> initData, String ParentNodeId)
	{
		List<TreeBean> list = new ArrayList<TreeBean>();
		
		//dataMap过滤
		List<Map<String,Object>> newDataMap = new ArrayList<Map<String, Object>>();
		for(Map<String,Object> item : dataMap)
		{
			if(ParentNodeId.equals(StringProcess.convertToString(item.get("ParentNodeId"))))
			{
				newDataMap.add(item);
			}
		}
		
		int count = newDataMap.size();
		int i = 0;
		for(Map<String,Object> item : newDataMap)
		{
			TreeBean node=new TreeBean();
			String nodeId = StringProcess.convertToString(item.get("NodeId"));
			node.setNodeId(nodeId);
			node.setNodeText(StringProcess.convertToString(item.get("NodeText")));
			node.setParentNodeId(StringProcess.convertToString(item.get("ParentNodeId")));
			
			//SelectType
			String nSelectType = StringProcess.convertToString(item.get("SelectType"));
			if(nSelectType.length()==0)
			{
				nSelectType = StringProcess.convertToString(selectType); 
			}
			if(nSelectType.equals("1"))
			{
				node.setSelectType("radio");
			}
			else if(nSelectType.equals("2"))
			{
				node.setSelectType("checkbox");
			}
			else
			{
				node.setSelectType("");
			}
			
			//IsLast
			if(i+1==count)
			{
				node.setLast(true);
			}
			
			//ClickScript
			String clickScript = StringProcess.convertToString(item.get("ClickScript"));
			if(clickScript.length()>0)
			{
				node.setClickScript(clickScript);
			}
			
			//ReturnValue
			String returnValue = StringProcess.convertToString(item.get("ReturnValue"));
			if(returnValue.length()>0)
			{
				node.setReturnValue(returnValue);
			}
			else
			{
				if(node.getSelectType().equals("1") || node.getSelectType().equals("2"))
				{
					//抛出错误：控件模式是单选框或多选框时，要有ReturnValue的值！
				}
				else
				{
					node.setReturnValue("");
				}
			}
			
			//IsSelect
			if(initData!=null && initData.size()>0)
			{
				for(Map<String,Object> initDataItem:initData)
				{
					if(nodeId.equals(initDataItem.get("NodeId")))
					{
						node.setSelect(true);
					}
				}
			}
			
			if(isLazy)
			{
				//AjaxFileName
				String ajaxFileName = StringProcess.convertToString(item.get("AjaxFileName"));
				if(ajaxFileName.length()>0)
				{
					node.setAjaxFileName(ajaxFileName);
				}
				else
				{
					//抛出错误：IsLazy等于true时，要有AjaxFileName的值！
				}
			}
			else
			{
				node.setChildNodes(dataTableToNode(dataMap,initData,node.getNodeId()));
				
				//OnlyLeafSelect
				if(onlyLeafSelect)
				{
					if(node.getChildNodes().size()>0)
					{
						node.setSelectType("");
					}
				}
			}
			
			list.add(node);
			
			i++;
			
		}
		
		return list;
	}
}
;